﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Dropbox
{
    public class DropboxHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (string.IsNullOrEmpty(context.Request.QueryString["dtdid"]))
                throw new ArgumentException("The querystring paramater 'dtdid' cannot be null or empty");

            var dtdid = Convert.ToInt32(context.Request.QueryString["dtdid"]);

            if (dtdid <= 0)
                throw new ArgumentException("The querystring paramater 'dtdid' must be a valid integer");

            var provider = UniversalMediaPickerProviderFactory.GetProvider<DropboxProvider>(dtdid);
            if (provider == null)
                throw new ArgumentException("The querystring paramater 'dtdid' does not resolve to a Dropbox provider");

            if (string.IsNullOrEmpty(context.Request.QueryString["path"]))
                throw new ArgumentException("The querystring paramater 'path' cannot be null or empty");

            var path = context.Request.QueryString["path"];

            var service = new DropboxService(provider.Config);

            var fileMetaData = service.GetMetaDataItem(path);

            if (fileMetaData.Is_Dir)
                throw new ArgumentException("The querystring paramater 'id' cannot resolve to a directory");

            if (fileMetaData.Is_Deleted)
                throw new ArgumentException("The querystring paramater 'id' cannot resolve to a deleted item");

            var fileBytes = service.GetFile(path);

            context.Response.Clear();
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileMetaData.Name);
            context.Response.AddHeader("Content-Length", fileBytes.Length.ToString());
            context.Response.ContentType = "application/octet-stream";
            context.Response.BinaryWrite(fileBytes); 
        }
    }
}